import { uReal, obj_str, d_sort, uDb, cline, for_obj } from 'sui';

const reload = (hDone, setMain, cur, mod="pair") => {
    uDb(hDone, `file/read/${mod}_${obj_str(cur, "sn")}`,
        {
            line: cline(),
        },
        r => {
            const ret = [];

            for_obj(r, (k, v) => ret.push(v));

            d_sort(ret, "sn");
            ret.forEach((d, i) => d["index"] = i + 1);

            setMain(ret);
        }, e => setMain(null));
};

const load_stock = (stockG, stockT) => {
    const cmd = { line: cline() };

    uDb(null, "stell/list", cmd, r => stockG(r), e => stockG(null));
    uDb(null, "cera/list", cmd, r => stockT(r), e => stockT(null));
};

const load_box = (setMain) => {
    uReal(null, "pair/sbox", { line: cline() },
        r => setMain(r),
        e => setMain(null));
};

const load_rule = (setRule) => {
    uDb(null, "code/get", { line: cline(), k: "task" },
        r => setRule(r),
        e => setRule(null));
};

const load_cage = (cur, setMain) => {
    const tsn = obj_str(cur, "sn");

    uDb(null, "cage/list", { line: cline() },
        r => {
            const ret = [];

            r.forEach(d => {
                const tech = obj_str(d, "tech");
                if (!tsn.startsWith(tech)) {
                    return;
                }

                ret.push({
                    sn: obj_str(d, "sn"),
                    name: obj_str(d, "stuffnum"),
                    num: obj_str(d, "num"),
                    ball: obj_str(d, "ball"),
                })
            });

            setMain(ret);
        },
        e => setMain(null));
};

export {load_cage, load_box, load_rule, load_stock, reload};
